const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // 去掉注释
const CompressionWebpackPlugin = require('compression-webpack-plugin'); // 开启压缩
const { HashedModuleIdsPlugin } = require('webpack');

function resolve(dir) {
	return path.join(__dirname, dir)
}

const isProduction = process.env.NODE_ENV === 'production';

// 转为CND外链方式的npm包，键名是import的npm包名，键值是该库暴露的全局变量，参考https://webpack.js.org/configuration/externals/#src/components/Sidebar/Sidebar.jsx
const externals = {
	vue: "Vue",
	"vue-router": "VueRouter",
	axios: "axios"
};
// CDN外链，会插入到index.html中
const cdn = {
	// 生产环境
	build: {
		js: [
			"https://unpkg.com/vue@2.6.10/dist/vue.min.js",
			"https://unpkg.com/vue-router@3.0.6/dist/vue-router.min.js",
			"https://unpkg.com/axios@0.19.0/dist/axios.min.js"
		]
	}
};

module.exports = {
	lintOnSave:false,
	publicPath: "./",
	assetsDir: "static",
	productionSourceMap: false,
	css: {
		extract: false,
		sourceMap: false,
		loaderOptions: {},
		modules: false
	},
	devServer: {
		open: false, // 自动启动浏览器
		host: '0.0.0.0', // localhost
		port: 6060, // 端口号
		https: false,
		hotOnly: false, // 热更新
		proxy: {
			'^/sso': {
				target: process.env.VUE_APP_SSO, // 重写路径
				ws: true,   //开启WebSocket
				secure: false,      // 如果是https接口，需要配置这个参数
				changeOrigin: true
			}
		}
	},

	pluginOptions: {
		"style-resources-loader": {
			patterns: [path.join(__dirname, "/src/assets/less/varibles.less")],
			preProcessor: "less"
		}
	},

	configureWebpack: config => {
		const plugins = [];

		if (isProduction) {
			plugins.push(
				new UglifyJsPlugin({
					uglifyOptions: {
						output: {
							comments: false, // 去掉注释
						},
						warnings: false,
						compress: {
							drop_console: true,
							drop_debugger: false,
							pure_funcs: ['console.log']//移除console
						}
					}
				})
			)
			// 服务器也要相应开启gzip
			plugins.push(
				new CompressionWebpackPlugin({
					algorithm: 'gzip',
					test: /\.(js|css)$/,// 匹配文件名
					threshold: 10000, // 对超过10k的数据压缩
					deleteOriginalAssets: false, // 不删除源文件
					minRatio: 0.8 // 压缩比
				})
			)

			// 用于根据模块的相对路径生成 hash 作为模块 id, 一般用于生产环境
			plugins.push(
				new HashedModuleIdsPlugin()
			)

			// 开启分离js
			config.optimization = {
				runtimeChunk: 'single',
				splitChunks: {
					chunks: 'all',
					maxInitialRequests: Infinity,
					minSize: 1000 * 60,
					cacheGroups: {
						vendor: {
							test: /[\\/]node_modules[\\/]/,
							name(module) {
								// 排除node_modules 然后吧 @ 替换为空 ,考虑到服务器的兼容
								const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
								return `npm.${packageName.replace('@', '')}`
							}
						}
					}
				}
			};

			// 取消webpack警告的性能提示
			config.performance = {
				hints: 'warning',
				//入口起点的最大体积
				maxEntrypointSize: 1000 * 500,
				//生成文件的最大体积
				maxAssetSize: 1000 * 1000,
				//只给出 js 文件的性能提示
				assetFilter: function (assetFilename) {
					return assetFilename.endsWith('.js');
				}
			}

			// 打包时npm包转CDN
			config.externals = externals;
		}

		return { plugins }
	},
	chainWebpack: config => {
		/**
		 * 删除懒加载模块的prefetch，降低带宽压力
		 * https://cli.vuejs.org/zh/guide/html-and-static-assets.html#prefetch
		 * 而且预渲染时生成的prefetch标签是modern版本的，低版本浏览器是不需要的
		 */
		config.plugins.delete("prefetch");
		// 压缩图片
		config.module
			.rule('images')
			.test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
			.use('image-webpack-loader')
			.loader('image-webpack-loader')
			.options({ bypassOnDebug: true })

		// webpack 会默认给commonChunk打进chunk-vendors，所以需要对webpack的配置进行delete
		config.optimization.delete('splitChunks')

		config.plugin('html').tap(args => {
			if (process.env.NODE_ENV === 'production') {
				args[0].cdn = cdn.build
			}
			if (process.env.NODE_ENV === 'development') {
				args[0].cdn = cdn.dev
			}
			return args
		})

		config
			.plugin('webpack-bundle-analyzer')
			.use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
	}
};
